<template>
  <div class="bg-white sticky top-0 left-0 z-10 dark:bg-zinc-900">
    <ul
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-500 overflow-hidden"
      ref="ulTarget"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] dark:bg-zinc-800 bg-zinc-900 rounded-lg duration-200"
      ></li>
      <!-- 汉堡按钮 -->
      <!-- right-[-1px] 特殊写法 -1 px -->
      <li
        class="z-20 fixed dark:bg-zinc-900 top-0 right-[-1px] h-4 px-1 flex items-center bg-white shadow-l-white dark:shadow-l-zinc"
        @click="onShowPopup"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
      <!-- category item -->
      <!-- last:mr-4 最后一个元素举例右侧的距离 -->

      <li
        v-for="(item, index) in $store.getters.categorys"
        :key="item.id"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-900 last:mr-4"
        :ref="setItemRef"
        @click="onItemClick(item)"
        :class="{
          ' text-zinc-100': $store.getters.currentCategoryIndex === index
        }"
      >
        {{ item.name }}
      </li>
    </ul>
    <m-popup v-model="isOpenPopup">
      <menu-vue @onItemClick="onItemClick"></menu-vue>
    </m-popup>
  </div>
</template>

<script setup>
import { nextTick, onBeforeUpdate, onMounted, ref, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import MenuVue from '../../menu/index.vue'
import { useStore } from 'vuex'
const store = useStore()
// 滑块
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '47px'
})
// 获取所有的item元素
let itemRefs = []
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}
const initSlider = (index) => {
  // 根据下标去找
  const { left, width } = itemRefs[index].getBoundingClientRect()
  // 滑块的位置 = 横向滚动的距离 + 当前元素的left(距离左侧) - ul的padding

  sliderStyle.value = {
    transform: `translateX(${ulScrollLeft.value + left - 10 + 'px'})`,
    width: width + 'px'
  }
}
// 初始化滑块的位置
onMounted(() => {
  initSlider(store.getters.currentCategoryIndex)
})

// 数据更新之后 dom变化之前清空数据
onBeforeUpdate(() => {
  itemRefs = []
})
// 获取 ul 元素
const ulTarget = ref(null)
// 获取响应式滚动距离
const { x: ulScrollLeft } = useScroll(ulTarget)
watch(
  () => store.getters.currentCategoryIndex,
  (val) => {
    initSlider(val)
  }
)

const onItemClick = (item) => {
  store.commit('app/changeCurrentCategory', item)

  if (isOpenPopup.value) {
    isOpenPopup.value = false
    // 弹层选中点击后 上方滚动条进行滚动距离调整 当前元素距离左侧 + ulTarget 的 scrollLeft
    ulTarget.value.scrollLeft = left + ulTarget.value.scrollLeft
  }
}
// 控制popup展示
const isOpenPopup = ref(false)
const onShowPopup = () => {
  isOpenPopup.value = true
}
</script>

<style scoped lang="scss"></style>
